<template>
  <div class="mt-15">
    <el-button v-if="checkPermission(permissionRoles.questionnaire_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加问卷</el-button>
    <el-table v-loading="listLoading" :data="list" class="mt-15" height="660" border>
      <el-table-column label="问卷ID" prop="id" width="50px" align="center"></el-table-column>
      <el-table-column label="问卷名称" prop="title" width="140px" align="center"></el-table-column>
      <el-table-column label="等级" prop="level" width="50px" align="center"></el-table-column>
      <el-table-column label="总充值金额" prop="amount" width="70px" align="center"></el-table-column>
      <el-table-column label="优先级" prop="sort" width="50px" align="center"></el-table-column>
      <el-table-column label="开始时间" prop="start_dt" width="135px" align="center"></el-table-column>
      <el-table-column label="结束时间" prop="end_dt" width="135px" align="center"></el-table-column>
      <el-table-column label="邮件标题" width="100px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.email_title === null">{{ row.email_title }}</span>
          <span v-else-if="row.email_title.length < 8">{{ row.email_title }}</span>
          <el-popover v-else trigger="hover" placement="top">
            <p>{{ row.email_title }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ row.email_title | sliceFilter }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="邮件内容" width="100px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.email_content === null">{{ row.email_content }}</span>
          <span v-else-if="row.email_content.length < 8">{{ row.email_content }}</span>
          <el-popover v-else trigger="hover" placement="top">
            <p>{{ row.email_content }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ row.email_content | sliceFilter }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="问卷奖励" prop="items_str" width="320px" align="center"></el-table-column>
      <el-table-column label="服务器" prop="show_sid" width="95px" align="center"></el-table-column>
      <el-table-column label="状态" prop="status" width="60px" align="center"></el-table-column>
      <el-table-column label="更新时间" prop="update_dt" width="135px" align="center"></el-table-column>
      <el-table-column label="操作人" prop="update_user" width="60px" align="center"></el-table-column>
      <el-table-column label="问卷内容" width="90px" align="center">
        <template slot-scope="{row}">
          <el-button v-if="row.config>0" type="text" size="small" title="查看" @click="handleView(row)">查看</el-button>
          <el-button v-if="checkPermission(permissionRoles.questionnaire_upload)" type="text" size="small" title="上传" @click="handleUpload(row)">上传</el-button>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="操作" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(permissionRoles.questionnaire_edit) && row.status !== '已结束'" type="text" size="small" title="编辑" @click="handleEdit(row)">修改</el-button>
          <el-button v-if="checkPermission(permissionRoles.questionnaire_edit) && row.status === '已结束'" type="text" size="small" title="查看" @click="handleEdit(row)">查看</el-button>
          <el-button v-if="checkPermission(permissionRoles.questionnaire_del)" type="text" size="small" title="删除" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="问卷名称" prop="title">
          <el-input v-model="dataForm.title" class="defaut-input" placeholder="请输入问卷名称" />
        </el-form-item>
        <el-form-item label="问卷内容" prop="content">
          <el-upload
            ref="upload"
            class="upload-demo"
            action=""
            :http-request="customUpload"
            :on-change="handleChange"
            :headers="header"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示等级">
          <el-input v-model="dataForm.level" class="defaut-input" placeholder="请输入显示等级" />
        </el-form-item>
        <el-form-item label="优先级" prop="sort">
          <el-input v-model="dataForm.sort" class="defaut-input" placeholder="请输入优先级" />
        </el-form-item>
        <el-form-item label="总充值金额" prop="amount">
          <el-input v-model="dataForm.amount" class="defaut-input" placeholder="总充值" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start_dt">
          <el-date-picker
            v-model="dataForm.start_dt"
            type="datetime"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_dt">
          <el-date-picker
            v-model="dataForm.end_dt"
            type="datetime"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="邮件标题" prop="email_title">
          <el-input v-model="dataForm.email_title" class="defaut-input" placeholder="填写邮件标题" />
        </el-form-item>
        <el-form-item label="邮件内容" prop="email_content">
          <el-input v-model="dataForm.email_content" type="textarea" :autosize="{ minRows: 3, maxRows: 8}" style="width: 60%;" />
        </el-form-item>

        <el-form-item label="奖励内容">
          <el-row>
            <el-col :md="3"><el-button type="primary" class="add" icon="el-icon-plus" @click="productAdd">新增</el-button></el-col>
          </el-row>
          <el-row
            v-for="(item, index) in dataForm.items"
            :key="index"
            class="mt-5"
            :gutter="12"
          >
            <el-col :md="6">
              <el-select v-model="item.id" clearable filterable placeholder="请选择物品">
                <el-option
                  v-for="p in products"
                  :key="p.id"
                  :label="p.desc"
                  :value="p.id"
                />
              </el-select>
            </el-col>
            <el-col :md="8"><el-input v-model="item.num" placeholder="数量" /></el-col>
            <el-col :md="4"><el-button type="danger" icon="el-icon-delete" @click.prevent="remove(item)" /></el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="服务器选择">
          <el-select v-model="server" clearable filterable style="width: 110px;" placeholder="请选择" @change="changeServer(server)">
            <el-option label="开服时间" value="1" />
            <el-option label="开服天数" value="2" />
          </el-select>
          <el-input v-show="showServerDay" v-model="serverDay.start" style="width: 80px;" placeholder="开始天数" />
          <el-input v-show="showServerDay" v-model="serverDay.end" style="width: 80px;" placeholder="结束天数" />
          <el-date-picker v-show="showServerDate" v-model="serverDate.start" type="date" style="width: 20%" placeholder="开始日期" />
          <el-date-picker v-show="showServerDate" v-model="serverDate.end" type="date" style="width: 20%" placeholder="结束日期" />
          <el-button type="primary" size="small" @click="searchServer()">搜索</el-button>
        </el-form-item>
        <el-form-item label="">
          <el-checkbox v-model="allServerChecked" @change="checkAllServer">显示全服</el-checkbox>
        </el-form-item>
        <div class="server-box">
          <ul class="menu-sub">
            <li
              v-for="(sgit,index) in serverGroups"
              :key="index"
            >
              <el-checkbox
                v-model="sgit.flag"
                :indeterminate="itemIndeterminate(sgit)"
                @change="(val) => handleCheckAll(val, sgit)"
              >{{ sgit.sgname }}</el-checkbox>
              <el-checkbox-group
                v-model="selectedData"
                style="padding-left: 30px;"
                @change="handleChanges(sgit)"
              >
                <el-checkbox
                  v-for="sgits in sgit.children"
                  :key="sgits.sid"
                  :label="sgits.sid"
                >{{ sgits.name }}</el-checkbox>
              </el-checkbox-group>
            </li>
          </ul>
        </div>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button v-if="viewBtn === true" type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleView" title="查看问卷" width="80%" :close-on-click-modal="false">
      <el-table v-loading="listLoading" :data="confList" height="560" border>
        <el-table-column label="问题ID" prop="qsid" width="70px" align="center"></el-table-column>
        <el-table-column label="标题" prop="title" width="500px" align="center"></el-table-column>
        <el-table-column label="选项内容" prop="content" align="center"></el-table-column>
        <el-table-column label="选项索引" prop="index_id" width="90px" align="center"></el-table-column>
        <el-table-column label="问卷ID" prop="qnid" width="70px" align="center"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleUpload" title="查看问卷" width="30%" :close-on-click-modal="false">
      <el-upload
        ref="upload"
        class="upload-demo"
        action=""
        :http-request="customUpload"
        :on-change="handleChange"
        :headers="header"
        :file-list="fileList"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios'
import checkPermission from '@/utils/permission' // 权限判断函数
import { getServerByDays, getServerListGroup } from '@/api/ops'
import { getQuestionnaireList, handleQuestionnaire, deleteQuestionnaire, getQuestionnaireConfList } from '@/api/operator'
import Pagination from '@/components/Pagination'
import { deepClone } from '@/utils'
import { getItemConfig } from '@/api/config'

const defaultItem = {
  id: '',
  title: '',
  level: '',
  amount: '',
  sort: '',
  start_dt: '',
  end_dt: '',
  email_title: '',
  email_content: '',
  sids: [],
  items: [{
    id: '',
    num: ''
  }]
}
export default {
  name: 'QuestionnaireList',
  components: { Pagination },
  filters: {
    sliceFilter(str) {
      return str.slice(0, 5)
    }
  },
  data() {
    return {
      header: {
        Authorization: this.$store.state.user.token
      },
      listLoading: false,
      viewBtn: true,
      permissionRoles: this.$store.state.user.permissionRoles,
      dataForm: Object.assign({}, defaultItem),
      serverDay: {
        start: '',
        end: ''
      },
      serverDate: {
        start: '',
        end: ''
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      searchServerGroups: [],
      serverGroups: [],
      products: [],
      fileList: [],
      confList: [],
      server: '',
      // uploadUrl: 'api/questionnaire/upload/',
      qid: '',
      total: 0,
      list: [],
      rules: {
        title: [{ required: true, message: '请填写问卷名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请填写优先级', trigger: 'blur' }],
        start_dt: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        end_dt: [{ required: true, message: '请选择结束时间', trigger: 'blur' }]
      },
      showServerDay: false,
      showServerDate: false,
      allServerChecked: false,
      selectedData: [],
      dialogVisible: false,
      dialogVisibleView: false,
      dialogVisibleUpload: false,
      dialogType: 'new',
      textMap: {
        new: '新增',
        edit: '编辑'
      }
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      this.listLoading = true
      getQuestionnaireList().then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    async getItemConfig() {
      const res = await getItemConfig()
      this.products = res.data.items
    },
    productAdd(row) {
      if (this.dataForm.items.length === 6) {
        return
      }
      this.dataForm.items.push({
        id: '',
        num: ''
      })
    },
    remove(row) {
      var index = this.dataForm.items.indexOf(row)
      if (index !== -1) {
        this.dataForm.items.splice(index, 1)
      }
    },
    handleAdd() {
      this.fileList = []
      this.viewBtn = true
      this.getItemConfig()
      this.serverListGroup(false)
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(row) {
      if (row.items === null) row.items = ''
      if (Array.isArray(row.items) === false) {
        if (row.items === '') {
          row.items = [{ id: '', num: '' }]
        } else {
          const items = JSON.parse(row.items)
          const a = []
          for (let i = 0; i < items.length; i++) {
            const o = { id: '', num: '' }
            o.id = items[i].itemId
            o.num = items[i].num
            a[i] = o
          }
          row.items = a
        }
      }
      if (row.status === '已结束') {
        this.viewBtn = false
      } else {
        this.viewBtn = true
      }
      this.fileList = []
      this.getItemConfig()
      this.serverListGroup(false)
      this.selectedData = row.sid
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.dataForm = deepClone(row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.sids = this.selectedData
          handleQuestionnaire(this.dataForm).then(response => {
            if (response.status) {
              this.qid = response.data
              this.submitUpload()
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    handleChange(file, fileList) {
      // 这里处理文件选择后的逻辑，比如更新fileList
      this.fileList = fileList
    },
    submitUpload() {
      // 触发自定义上传
      this.fileList.forEach(file => {
        this.customUpload(file)
      })
    },
    customUpload(file) {
      const formData = new FormData()
      formData.append('file', file.raw) // 添加文件
      formData.append('qid', this.qid) // 添加额外数据
      axios.post('api/questionnaire/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': this.$store.state.user.token
        }
      }).then(response => {
        if (this.dialogVisibleUpload === true) {
          this.$message({
            type: 'success',
            message: '上传问卷成功!'
          })
          this.dialogVisibleUpload = false
        }
        // 处理响应
        if (response.code === 40000) {
          this.message.error('问卷内容上传失败')
        }
      }).catch(error => {
        // 处理错误
        this.message.error('问卷内容上传失败' + error)
      })
    },

    handleDelete(row) {
      this.$confirm('你确定要删除此行数据吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteQuestionnaire(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },

    changeServer(val) {
      if (val === '1') {
        this.showServerDate = true
        this.showServerDay = false
      } else {
        this.showServerDay = true
        this.showServerDate = false
      }
    },

    handleView(row) {
      this.dialogVisibleView = true
      this.getConfList(row)
    },

    async getConfList(row) {
      getQuestionnaireConfList({ qnid: row.id }).then(response => {
        this.confList = response.data
      })
    },

    handleUpload(row) {
      this.dialogVisibleUpload = true
      this.fileList = []
      this.qid = row.id
    },

    async serverListGroup(val) {
      getServerListGroup({ all: val }).then(res => {
        this.serverGroups = res.data
      })
    },

    searchServer() {
      const item = {
        server: this.server,
        allServer: this.allServerChecked,
        data: {}
      }
      if (this.server === '1') {
        item.data = this.serverDate
      } else {
        item.data = this.serverDay
      }
      getServerByDays(item).then(response => {
        this.selectedData = response.data
      })
    },

    // 全选
    handleCheckAll(val, item) {
      // 过滤掉没有选中的数据，item.child中不包含v时返回-1
      const next = item.children.map(item => item.sid)
      const filterArr = this.selectedData.filter(
        (v) => next.indexOf(v) === -1
      )
      this.selectedData = val ? filterArr.concat(next) : filterArr
    },
    itemIndeterminate(item) {
      const infoLists = item.children.map(ite => ite.sid)
      return (
        infoLists.some((v) => this.selectedData.indexOf(v) > -1) &&
        !infoLists.every((v) => this.selectedData.indexOf(v) > -1)
      )
    },
    // 勾选变化方法
    handleChanges(val) {
      const infoLists = val.children.map(ite => ite.sid)
      infoLists.every((v) => {
        if (this.selectedData.indexOf(v) > -1) {
          val.flag = true
        } else {
          val.flag = false
        }
      })
    },
    checkAllServer() {
      this.serverListGroup(this.allServerChecked)
    }
  }
}
</script>

<style>
.el-tabs__header {
  margin: 0px;
}
</style>
